package leetcode.D200.T160;

import util.ListNode;

/**
 * @File Info: leetcode -- <Solution>
 * @Author: DYZ
 * @Create: 2022-02-18 13:20:49
 */

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode tailA = findTail(headA);
        ListNode tailB = findTail(headB);
        if (tailA != tailB)
            return null;
        ListNode pA = headA, pB = headB;
        while (pA != pB) {
            if (pA.next == null)
                pA = headB;
            else
                pA = pA.next;
            if (pB.next == null)
                pB = headA;
            else
                pB = pB.next;
        }
        return pA;
    }

    private ListNode findTail(ListNode head) {
        while (head.next != null) {
            head = head.next;
        }
        return head;
    }
}
